/* eslint-disable no-undef */
<template>
  <div class="thermodynamic">
    <div id="container" />
    <slot />
  </div>
</template>

<script>
/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
/* eslint-disable vue/require-default-prop */
import loadBMap from "../js/loadBMap"

export default {
  name: "MapBd",
  data() {
    return {
      myMap: {},
      drawingManager: {},
      menu: {},
      markerList: [],
      geocoder: {}
    }
  },
  props: {
    pointList: {
      type: Array
    },
    city: {
      type: String
    },
    singlePoint: {
      type: Boolean
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.getMyMap()
    })
  },
  methods: {
    // 初始化地图
    async getMyMap() {
      loadBMap(this.$ocean.BMapAK)
        .then(() => {
          this.myMap = new BMap.Map("container", { enableMapClick: false })
          this.myMap.centerAndZoom('北京')
          this.myMap.centerAndZoom(this.city)
          // this.myMap.centerAndZoom(new BMap.Point(116.404, 39.915), 11)
          // this.myMap.setCurrentCity("北京") // 设置地图显示的城市
          this.myMap.enableScrollWheelZoom(true) //开启鼠标滚轮缩放
          // 地理编码
          this.geocoder = new BMap.Geocoder();

          let styleOptions = {
            strokeColor: "red", //边线颜色。
            fillColor: "red", //填充颜色。当参数为空时，圆形将没有填充效果。
            strokeWeight: 3, //边线的宽度，以像素为单位。
            strokeOpacity: 0.8, //边线透明度，取值范围0 - 1。
            fillOpacity: 0.6, //填充的透明度，取值范围0 - 1。
            strokeStyle: "solid", //边线的样式，solid或dashed。
          }
          //实例化鼠标绘制工具
          this.drawingManager = new BMapLib.DrawingManager(this.myMap, {
            isOpen: false, //是否开启绘制模式
            enableDrawingTool: true, //是否显示工具栏
            drawingToolOptions: {
              anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
              offset: new BMap.Size(5, 5), //偏离值
            },
            markerOptions: {enableDragging: true},
            circleOptions: styleOptions, //圆的样式
            polylineOptions: styleOptions, //线的样式
            polygonOptions: styleOptions, //多边形的样式
            rectangleOptions: styleOptions, //矩形的样式
          })
          // 设置绘图模式为点模式
          this.drawingManager.setDrawingMode('marker')
          this.drawingManager.addEventListener('overlaycomplete', this.overlaycomplete)
          // this.drawingManager.addEventListener('markercomplete', this.markercomplete)

          // 绘制默认点
          if(this.pointList.length > 0) {
            this.pointList.map(async item => {
              this.addPoint(item)
            })
          }
        })
        .catch((err) => {
          console.log('异步加载失败：' + err)
        })
    },
    // 切换城市
    switchCity(city) {
      this.myMap.centerAndZoom(city)
    },
    // 坐标系转换
    coordinateTranslate(point) {
      return new Promise((resolve, reject) => {
        if (point.coordinateType === 3) return resolve(point)
        let convertor = new BMap.Convertor()
        let pointArr = [new BMap.Point(point.lng,point.lat)];
        let from = point.coordinateType === 2 ? 3 : 1
        convertor.translate(pointArr, from, 5, (data) => {
          if(data.status === 0) {
            let p =  data.points[0]
            let i = this.$ocean.deepClone(point)
            i.lng = p.lng
            i.lat = p.lat
            i.coordinateType = 3
            i.pointId = point.pointId
            resolve(i)
          } else {
            console.log('坐标转换失败')
            reject()
          }
        })
      })
    },
    // 鼠标工具添加完点的回调
    overlaycomplete(el) {
      // if(this.singlePoint) {
      //   this.markerList.map(item => {
      //     this.deletePoint(item)
      //   })
      //   this.markerList = []
      // }
      // el.overlay.pointId = new Date().getTime()
      // this.$nextTick(() => {
      //   // 添加到点列表
      //   let pointList = deepClone(this.pointList)
      //   pointList.push({
      //     lng: el.overlay.getPosition().lng,
      //     lat: el.overlay.getPosition().lat,
      //     pointId: el.overlay.pointId,
      //     coordinateType: 3
      //   })
      //   this.$emit('update:pointList', pointList)
      //   this.pointFun(el.overlay)
      //   this.markerList.push(el.overlay)
      // })

      // console.log(el.drawingMode)
      switch(el.drawingMode) {
        case 'marker':
          this.markercomplete(el.overlay)
          break
        case 'polygon':
          this.polygoncomplete(el.overlay)
      }
    },
    // 鼠标工具-添加完点的回调
    markercomplete(marker) {
      if(this.singlePoint) {
        this.markerList.map(item => {
          this.deletePoint(item)
        })
        this.markerList = []
      }
      marker.pointId = new Date().getTime()
      this.$nextTick(() => {
        // 添加到点列表
        let pointList = this.$ocean.deepClone(this.pointList)
        pointList.push({
          lng: marker.getPosition().lng,
          lat: marker.getPosition().lat,
          pointId: marker.pointId,
          coordinateType: 3
        })
        this.$emit('update:pointList', pointList)
        this.pointFun(marker)
        this.markerList.push(marker)
      })
    },
    // 鼠标工具-添加完多边形的回调
    polygoncomplete(polygon) {
      console.log(polygon.getPath())
      polygon.enableEditing()
      this.$parent.drag()
    },
    // 配置点功能
    pointFun(el) {
      // 添加点击事件
      el.addEventListener("click",(e) => {
        this.openInfo(el)
      })
      // 添加拖拽中事件
      el.addEventListener("dragging",(e) => {
        this.myMap.closeInfoWindow()
        // this.openInfo(el) // 移动时不关闭信息窗口
      })
      // 添加拖拽结束事件
      el.addEventListener("dragend",(e) => {
        this.deitPoint(el)
      })
      // 添加右键菜单
      let menu = new BMap.ContextMenu();
      menu.addItem(new BMap.MenuItem('删除', () => {
        this.deletePoint(el)
      }))
      el.addContextMenu(menu)
    },
    // 配置中心点及缩放级别
    async setCenterZoom(option) {
      // 设置中心点
      if (option.center) {
        let point = await this.coordinateTranslate(option.center)
        this.myMap.setCenter(new BMap.Point(point.lng,point.lat))
      }
      // 设置缩放级别
      if (option.zoom) {
        this.myMap.setZoom(option.zoom)
      }
    },
    /**
     * 获取点详细地址
     * @param {Object} point - 坐标点信息
     * @param {number} point.lng - 经度
     * @param {number} point.lat - 纬度
     * @param {number} point.coordinateType - 坐标系类型
     */ 
    async getAddress(point) {
      if (point.coordinateType !== 3) {
        let p =  await this.coordinateTranslate(point)
        let i = this.$ocean.deepClone(point)
        i.lng = p.lng
        i.lat = p.lat
        i.coordinateType = 3
        point = i
      }
      return new Promise((resolve, reject) => {
        this.geocoder.getLocation(new BMap.Point(point.lng,point.lat),res => {
          if(res) {
            resolve(Object.assign({
              formattedAddress: res.address,// 完整地址
              adcode: '000000',// 邮政编码
              citycode: '0000',// 固定电话区号
              district: res.addressComponents.district,// 区
              province: res.addressComponents.province,// 省
              city: res.addressComponents.city,// 市
              street: res.addressComponents.street,// 街道
              streetNumber: res.addressComponents.streetNumber, // 街道号
              township: res.addressComponents.town,// 镇
            },point))
          }else{
            console.error('地址解析失败')
            reject()
          }
        })
      })
    },
    // 新增点
    async addPoint(el){
      if (el.coordinateType !== 3) {
        let point =  await this.coordinateTranslate(el)
        let i = this.$ocean.deepClone(el)
        i.lng = point.lng
        i.lat = point.lat
        i.coordinateType = 3
        el = i
      }
      let marker = new BMap.Marker(new BMap.Point(el.lng, el.lat),{
        enableDragging: true
      })
      marker.pointId = el.pointId
      this.pointFun(marker)
      this.myMap.addOverlay(marker)
      this.markerList.push(marker)
    },
    // 修改点
    deitPoint(el){
      let pointList = deepClone(this.pointList)
      let point = el.getPosition()
      pointList.map((item, index) => {
        if(el.pointId === item.pointId) {
          item.lng = point.lng
          item.lat = point.lat
          item.coordinateType = 3
        }
      })
      this.$emit('update:pointList', pointList)
    },
    // 删除点
    deletePoint(el) {
      this.myMap.removeOverlay(el)
      let pointList = this.$ocean.deepClone(this.pointList)
      pointList.map((item, index) => {
        if(el.pointId === item.pointId) {
          pointList.splice(index,1)
        }
      })
      this.$emit('update:pointList', pointList)
      this.markerList.map((item, index) => {
        if(el.pointId === item.pointId) {
          this.markerList.splice(index,1)
        }
      })
    },
    // 展示信息
    openInfo(e) {
      let opts = {
				width : 250,     // 信息窗口宽度
				height: 80,     // 信息窗口高度
				title : "该点坐标" , // 信息窗口标题
				enableMessage:true//设置允许信息窗发送短息
      }
      let point = new BMap.Point(e.getPosition().lng, e.getPosition().lat);
      let infoWindow = new BMap.InfoWindow('经度：' + e.getPosition().lng.toFixed(6) + '<br>纬度：' + e.getPosition().lat.toFixed(6), opts);  // 创建信息窗口对象 
      this.myMap.openInfoWindow(infoWindow,point); //开启信息窗口
    },
    // 返回地图信息
    getMapInfo() {
      let zoom = this.myMap.getZoom()
      let center = this.myMap.getCenter()
      center = {
        lat: center.lat,
        lng: center.lng,
        coordinateType: 3
      }
      return { zoom, center }
    },
    // 清空覆盖物
    clearOverlay() {
      this.myMap.clearOverlays()
    },
    // 工具-拖动
    drag() {
      this.drawingManager.close()
    },
    // 工具-画点
    drawSome() {
      this.drawingManager.setDrawingMode('marker')
      this.drawingManager.open()
    },
    // 工具-绘制多边形
    drawArea() {
      this.drawingManager.setDrawingMode('polygon')
      this.drawingManager.open()
    },
  },
}
</script>

<style lang="scss" scoped>
.thermodynamic {
  width: 100%;
  height: 100%;
  #container {
    width: 100%;
    height: 100%;
  }
}
</style>
